package com.litchishell.easy;

/**
 * @author LitchiShell
 * @description: 题目27：移除元素
 * @create 2022-08-22
 */
public class Solution008 {

    // 常规题解
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int index = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                index++;
                nums[index] = nums[i];
            }
        }
        return index >= 0 ? index + 1 : 0;
    }

    // 官方题解
    public int removeElementCopy(int[] nums, int val) {
        int left = 0;
        int right = nums.length;
        while (left < right) {
            if (nums[left] == val) {
                nums[left] = nums[right - 1];
                right--;
            } else {
                left++;
            }
        }
        return left;
    }
}
